<!--
 * @Date: 2023-02-27 21:10:09
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-28 18:56:31
 * @FilePath: \A19\frontend\src\components\Class\TheWorld.vue
-->
<!--
 * @Date: 2023-02-27 21:10:09
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-15 15:40:28
 * @FilePath: \A19\frontend\src\components\Class\TheWorld.vue
-->
<template>
  <World>
    <Model :scale="300" src="/models/Grassland.glb" physics="map" name="map" toon>
    </Model>
    <Model
      src="/models/ki.fbx"
      physics="map"
      name="ki"
      :width="86.49"
      :depth="11.46"
      :x="-2116.92"
      :y="-876.69"
      :z="1038.17"
      :rotation-y="90"
      :scale="10"
    ></Model>
    <!-- <Model :y="-642.00" :scale="10" src="/models/cinema.glb" physics="map" name="map" toon>
        <Find name="Cube.300_White_0" :video-texture="el"></Find>
      </Model> -->

    <Plane
      :video-texture="el"
      ref="plane"
      :x="-2076.29"
      :y="-722.92"
      :z="1036.79"
      :rotation-y="90"
      :width="1920"
      :height="1080"
      :scale="0.4"
      @mouse-over="watchIn"
      @mouse-out="watchOff"
    >
    </Plane>

    <!-- <Plane
     :rotation-y="270" 
     :video-texture="el" 
     ref="plane" 
     :x="-944.21" 
     :y="-687.64"
     :z="-1632.14" 
     :width="1920" 
     :height="1080"
     :scale="0.46"
     @mouse-over="watchIn" 
     @mouse-out="watchOff"
    >
    </Plane>

    <Plane
     :rotation-y="90" 
     :video-texture="el" 
     ref="plane" 
     :x="-937.36" 
     :y="-687.64"
     :z="-1632.14" 
     :width="1920" 
     :height="1080"
     :scale="0.46"
     @mouse-over="watchIn" 
     @mouse-out="watchOff"
    >
    </Plane>

    <Plane
     :rotation-y="90" 
     :video-texture="el" 
     ref="plane" 
     :x="-930.25" 
     :y="-687.64"
     :z="-1632.14" 
     :width="1920" 
     :height="1080"
     :scale="0.46"
     @mouse-over="watchIn" 
     @mouse-out="watchOff"
    >
    </Plane>

    <Plane
     :rotation-y="90" 
     :video-texture="el" 
     ref="plane" 
     :x="-925.96" 
     :y="-687.64"
     :z="1621.23" 
     :width="1920" 
     :height="1080"
     :scale="0.46"
     @mouse-over="watchIn" 
     @mouse-out="watchOff"
    >
    </Plane>

    <Plane
     :rotation-y="270" 
     :video-texture="el" 
     ref="plane" 
     :x="-938.99" 
     :y="-687.64"
     :z="1621.23" 
     :width="1920" 
     :height="1080"
     :scale="0.46"
     @mouse-over="watchIn" 
     @mouse-out="watchOff"
    >
    </Plane> -->

    <!-- mouseControl="drag" -->
    <!-- lockTargetRotation="dynamic-lock" -->
    <ThirdPersonCamera
      active
      mouseControl
      lockTargetRotation="dynamic-lock"
      enableDamping
      :inner-x="110"
      :inner-y="camYSpring"
      :inner-z="camZSpring"
      :inner-rotation-x="-5"
      :inner-rotation-y="3.5"
      :fov="60"
    >
      <!--  strideMode="aim | free" -->
      <!-- Fox.fbx  enderman.fbx-->
      <Dummy
        ref="foxRef"
        :src="`/models/${char}/char.fbx`"
        :animations="{
          idle: `/models/${char}/Idle.fbx`,
          running: `/models/${char}/Walking.fbx`,
        }"
        :y="-968.56"
        :strideMove="true"
        strideMode="free"
        physics="character"
        :metalnessFactor="-5"
        :box-visible="false"
      >
        <HTMLMesh :sprite="true" :scale="0.3" :y="56" v-if="start">
          <div class="username">
            {{ currentUser.name }}
          </div>
        </HTMLMesh>
      </Dummy>
    </ThirdPersonCamera>

    <!--  :ref="getPlayerRefs"
  v-for="(player,id) in players"
 -->
    <Dummy
      v-for="(dummyProxy,playerId) in dummyProxies"
      :src="`/models/${dummyProxy.model}/char.fbx`"
      :animations="{
        idle: `/models/${dummyProxy.model}/Idle.fbx`,
        running: `/models/${dummyProxy.model}/Walking.fbx`,
      }"
      physics="character"
      :metalnessFactor="-5"
      :key="playerId"
      :proxy="dummyProxy"
      preset="rifle"
    >
      <HTMLMesh :sprite="true" :scale="0.3" :y="56" v-if="dummyProxy.playerName">
        <div class="username">
          {{ dummyProxy.playerName }}
        </div>
      </HTMLMesh>
    </Dummy>

    <!-- <Joystick :onMove="joyMove" :onMoveEnd="joyMoveEnd" v-if="joyDisplay" /> -->
    <Setup skybox="/env/env.hdr" :exposure="1" :pixel-ratio="ratio || 1"/>
    <LingoEditor v-if="editorOn" />
  </World>
</template>

<script lang="ts" setup>
import {World,Lingo,Model,Find,ThirdPersonCamera,Dummy,HTMLMesh,Joystick,Setup,LingoEditor,Plane, createProxy} from 'lingo3d-vue'
import { editController } from '../../hooks/world/editController';
import { joyDisplayController } from '@/hooks/world/joyDisplayController';
import { useClientStore } from '../../pinia/stores/client';
import { onMounted, ref, Ref, onUnmounted, inject, reactive,computed } from 'vue';
import { keyActionshook } from '@/hooks/world/keyActions';
import mitt from '@/mitt';
import { RTCConnection } from '@/utils/RTCConnection';
import { createVidoehook } from '../../hooks/world/createVideohook';
import { watching } from '@/hooks/world/watchingHook'
// import { SyncHook } from '../../hooks/world/playerSync';
import { ServiceType } from '@/shared/protocols/serviceProto';
import { WsClient } from 'tsrpc-browser';
import router from '@/route';
import { MsgPlayerJoin } from '@/shared/protocols/AMessages/Game/MsgPlayerJoin';

const { currentUser } = useClientStore()
const foxRef = ref<Lingo.Dummy>();
const plane = ref<Lingo.Plane>()
const start = ref(true)

const chars = ['fox' , 'person']
const char = ref<'fox' | 'person'>(chars[Math.floor(Math.random() * 2)] as 'fox' | 'person')

//inject
const wsClient = inject<WsClient<ServiceType>>('wsclient')
// const rtc = inject<Ref<RTCConnection>>('rtc')
const el = inject<Ref<HTMLVideoElement>>('el')
const courseId = inject<string>('courseId')
const ratio = inject<Ref<number>>('ratio')

//hooks
const { editorOn } = editController()
const {keyActions,stopWalk} = keyActionshook(foxRef,currentUser,wsClient,courseId as string)
const { watchIn,watchOff,camYSpring,camZSpring, } = watching()
// const { el } = createVidoehook()
if(!courseId) router.back()

// const playerProxys = reactive(new Map<string,Lingo.Dummy>)
// const players = reactive(new Array<MsgPlayerJoin>())
const spawn = {
  x: 0,
  y: -968.56,
  z: 0,
  strideForward:0,
  strideRight:0,
  animation: 'idle',
  rotationX: 0,
  rotationY: 0,
  rotationZ: 0,
}
// const getPlayerRefs = (dummy:any)=>{
//   if(!dummy || !dummy.id ) return
//   playerProxys.set(dummy.id,dummy)
// } 
interface theDummy extends Lingo.Dummy{
  model:string
  playerName:string
}

const dummyProxies = reactive<Record<string,theDummy>>({})

wsClient?.listenMsg('AMessages/Game/UpdateStatus',msg =>{
  // msg.userId
  
  if(msg.playerId !== currentUser._id){
    // const dummy = playerProxys.get(msg.userId)
    const dummy = dummyProxies[msg.playerId]
    if(dummy){
      // dummy.moveTo(msg.x,msg.y,msg.z,6)
      Object.assign(dummy,msg)
      // const { strideRight,strideForward,animation,rotationX,rotationY,rotationZ } = msg
      // Object.assign(dummy,{
      //   strideForward,
      //   strideRight,
      //   animation,
      // })
    }
  }
})
wsClient?.listenMsg('AMessages/Game/PlayerJoin',msg =>{
  if(msg.playerId !== currentUser._id){
    // players.push(msg)
    const dummy = dummyProxies[msg.playerId] = createProxy<theDummy>()
    Object.assign(dummy,msg)
  }
})
wsClient?.listenMsg('AMessages/Game/PlayerLeave',msg =>{
  // players.find((player,index,arr) => {
  //   if(player.playerId === msg.playerId){
  //     arr.splice(index,1)
  //     playerProxys.delete(player.playerId)
  //     return true
  //   }
  //   return false
  // })
  delete dummyProxies[msg.playerId]
})

onMounted(() =>{
    keyActions(char.value)
    wsClient?.sendMsg('AMessages/Game/PlayerJoin',{
      liveId:courseId as string,
      playerId:currentUser._id,
      playerName:currentUser.name,
      ...spawn,
      model:char.value
    })
})
onUnmounted(()=>{
  mitt.off("trackReady")

  wsClient?.sendMsg('AMessages/Game/PlayerLeave',{
    playerId:currentUser._id,
    liveId:courseId as string
  })
})
</script>

<style lang="less" scoped>
.username {
  color: #fff;
  font-size: 36px;
  line-height: 50px;
  height: 50px;
}
</style>
